package com.ziq.zcamp.place

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Paint
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.GsonUtils
import com.ziq.base.extension.BindingViewHolder
import com.ziq.base.extension.click
import com.ziq.base.extension.createBindingViewHolder
import com.ziq.base.extension.dp
import com.ziq.zcamp.bean.place.CampListItem
import com.ziq.zcamp.bean.place.PlaceListItem
import com.ziq.zcamp.bean.post.ImageInfo
import com.ziq.zcamp.databinding.ItemCampListBinding
import com.ziq.zcamp.extension.pageClick
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.PrivacyManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.place.PlaceListFragmentViewModel.Companion.empty_id
import com.ziq.zcamp.util.ImageUtil
import java.text.DecimalFormat

//只能营地列表使用
class CampListAdapter() : RecyclerView.Adapter<BindingViewHolder<ItemCampListBinding>>(){

     val placeList : MutableList<CampListItem> = mutableListOf()
     var onPlaceClickListener : OnPlaceClickListener? = null

     fun setData(list: List<CampListItem>){
         placeList.clear()
         placeList.addAll(list)
         notifyDataSetChanged()
     }

    override fun getItemCount(): Int {
        return placeList.size
    }

     override fun getItemId(position: Int): Long {
         return position.toLong()
     }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BindingViewHolder<ItemCampListBinding> {
        return createBindingViewHolder(parent)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(
        holder: BindingViewHolder<ItemCampListBinding>,
        position: Int
    ) {
        val item = placeList[position]

        if(item.id == empty_id){
            holder.binding.cardview.visibility = View.GONE
            holder.binding.ivTag.visibility = View.GONE
            holder.binding.llMoreStatus.visibility = View.VISIBLE
            if(position == 0){
                holder.binding.tvMoreStatus.text = "- 暂无相关营地 -"
            } else {
                holder.binding.tvMoreStatus.text = "- 筛选结果展示完毕 -"
            }
            holder.itemView.click {}
        } else {
            holder.binding.cardview.visibility = View.VISIBLE
            holder.binding.ivTag.visibility = View.GONE
            holder.binding.llMoreStatus.visibility = View.GONE

            var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
            if (item.pictures?.isNotEmpty() == true){
                item.pictures?.let {
                    imageList = GsonUtils.fromJson(it, GsonUtils.getListType(ImageInfo::class.java))
                }
            }

            holder.binding.imagesBanner.children.find { it is ViewPager2 }?.let { pager->
                (pager as ViewPager2).children.find { it is RecyclerView }?.let {
                    (it as RecyclerView).isNestedScrollingEnabled = false
                }
            }
            holder.binding.pageLineIndicator.setForceFromStart(true)
            holder.binding.pageLineIndicator.updatePaint(setting = { backgroundPaint: Paint, foregroundPaint: Paint ->
                backgroundPaint.strokeWidth = 4.dp.toFloat()
                backgroundPaint.setStrokeCap(Paint.Cap.ROUND)
                backgroundPaint.setColor(Color.parseColor("#33000000"))
                foregroundPaint.strokeWidth = 4.dp.toFloat()
                foregroundPaint.setStrokeCap(Paint.Cap.ROUND)
                foregroundPaint.setColor(Color.parseColor("#ffffff"))
            })





            holder.binding.imagesBanner.setAutoPlay(false)
            holder.binding.imagesBanner.setCanLoop(false)
            holder.binding.imagesBanner.setIndicatorVisibility(View.GONE)
            holder.binding.imagesBanner.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    holder.binding.pageLineIndicator.setPageIndex(imageList.size, position)
                }
            })
            holder.binding.imagesBanner.pageClick { clickedView, position ->
                onPlaceClickListener?.onPlaceClick(item)
            }

            if(holder.binding.imagesBanner.getTag() != "${item.id}"){
                holder.binding.imagesBanner.setAdapter(ImageBannerAdapter())
                holder.binding.imagesBanner.create(imageList)
                holder.binding.pageLineIndicator.setPageIndex(imageList.size, 0)
            }
            holder.binding.imagesBanner.setTag("${item.id}")

            holder.itemView.click {
                onPlaceClickListener?.onPlaceClick(item)
            }

            holder.binding.name.text = item.campName

            holder.binding.btnCollect.isSelected = item.is_collect?:false
            UserManager.instance.campCollect.value?.let {
                if(it.containsKey(item.id)){
                    holder.binding.btnCollect.isSelected = it[item.id] == 0
                }
            }

            holder.binding.btnCollect.click {
                LoginActivity.checkLogin ( object : ActionAfterLogin {
                    override fun action() {
                        UserManager.instance.apply {
                            if(isLogin.value == true){
                                if(holder.binding.btnCollect.isSelected){
                                    collectCamp(item.id?:0, 1, onSuccessAction = {
                                        item.is_collect = false
                                        holder.binding.btnCollect.isSelected = false
                                    })
                                } else {
                                    collectCamp(item.id?:0, 0, onSuccessAction = {
                                        item.is_collect = true
                                        holder.binding.btnCollect.isSelected = true
                                    })
                                }
                            }
                        }

                    }
                })
            }


//            if(item.tag != null && item.tag?.position == 1){
//                holder.binding.ivTag.visibility = View.VISIBLE
//                val lp = holder.binding.ivTag.layoutParams
//                lp.width = item.tag?.image_width?:71.dp
//                lp.height = item.tag?.image_height?:14.dp
//                holder.binding.ivTag.layoutParams = lp
//                ImageUtil.updateImageFromNetwork(holder.binding.ivTag, item.tag?.image?:"")
//            } else {
//                holder.binding.ivTag.visibility = View.GONE
//            }
//
//
//
//            var hasTopLabel = item.rank?.country_rank != null || item.rank?.province_rank != null
//            if(hasTopLabel){
//                holder.binding.llTopLabel.visibility = View.VISIBLE
//                if(item.rank?.country_rank != null){
//                    holder.binding.tvTopLabel.text = "全国热门营地榜·Top${item.rank?.country_rank?.rank}"
//                } else if(item.rank?.province_rank != null){
//                    holder.binding.tvTopLabel.text = "${item.rank?.province_rank?.district?.name}热门营地榜·Top${item.rank?.province_rank?.rank}"
//                }
//            } else {
//                holder.binding.llTopLabel.visibility = View.GONE
//                holder.binding.tvTopLabel.text = ""
//            }


            val distance = item.distance?.toFloat()
            if(distance != null){
                distance.let {
                    holder.binding.tvLabelDistance.text = "${DecimalFormat("0.##").format(distance / 1000)}km"
                }
            } else {
                holder.binding.tvLabelDistance.text = ""
            }


            var hasScore = false
            if (item.score == null || item.score == 0.0){
                hasScore = false
                holder.binding.llLabelStars.visibility = View.GONE
            }else{
                hasScore = true
                holder.binding.llLabelStars.visibility = View.VISIBLE
                holder.binding.tvLabelStars.text = "${DecimalFormat("0.0").format((item.score?:0.0) / 10f)}分"
            }

//            var hasCouponLabel = item.coupon_tag?.stock_id?.isNotEmpty() == true
//            if(hasCouponLabel){
//                holder.binding.llLabelCoupon.visibility = View.VISIBLE
//                holder.binding.tvLabelCoupon.text = "${item.coupon_tag?.coupon_title}"
//            } else {
//                holder.binding.llLabelCoupon.visibility = View.GONE
//                holder.binding.tvLabelCoupon.text = ""
//            }
//
//            if(hasScore && hasCouponLabel){
//                holder.binding.llLabelVr.isVisible = false
//            } else {
//                holder.binding.llLabelVr.isVisible = item.exist_vr == true
//            }
//
//            holder.binding.clProduct1.click {  }
//            holder.binding.clProduct2.click {  }
//
//            if(item.commodity_info?.isNotEmpty() == true){
//                holder.binding.clProduct1.isVisible = true
//                item.commodity_info?.get(0)?.let {
//                    holder.binding.clProduct1.click { view->
//                        GlobalContextManager.getCurrentActivity()?.let { act->
//                            PrivacyManager.checkPrivacy(act, action = {
//                                PlaceProductDetailActivity.open(GlobalContextManager.appContext!!, it.commodity_id?:0, source = "home_camp_list")
//                            })
//                        }
//                    }
//                    holder.binding.tvProduct1.text = it.name
//                    if(it.url?.isNotEmpty() == true){
//                        val imageUrl = it.url?.get(0)
//                        ImageUtil.updateImageFromNetwork(holder.binding.ivProduct1, imageUrl?.url)
//                    }
//                    if((it.price_range?.size?:0) > 0){
//                        val li = it.price_range?.sortedBy { it }
//                        holder.binding.tvProductPrice1.text = "${DecimalFormat("0.00").format((li?.first()?:0) / 100f)}"
//                    }else {
//                        holder.binding.tvProductPrice1.text = "${DecimalFormat("0.00").format((it.price?:0) / 100f)}"
//                    }
//                }
//                if((item.commodity_info?.size?:0) > 1){
//                    holder.binding.clProduct2.isVisible = true
//                    item.commodity_info?.get(1)?.let {
//                        holder.binding.clProduct2.click { view->
//                            GlobalContextManager.getCurrentActivity()?.let { act->
//                                PrivacyManager.checkPrivacy(act, action = {
//                                    PlaceProductDetailActivity.open(GlobalContextManager.appContext!!, it.commodity_id?:0, source = "home_camp_list")
//                                })
//                            }
//                        }
//                        holder.binding.tvProduct2.text = it.name
//                        if(it.url?.isNotEmpty() == true){
//                            val imageUrl = it.url?.get(0)
//                            ImageUtil.updateImageFromNetwork(holder.binding.ivProduct2, imageUrl?.url)
//                        }
//                        if((it.price_range?.size?:0) > 0){
//                            val li = it.price_range?.sortedBy { it }
//                            holder.binding.tvProductPrice2.text = "${DecimalFormat("0.00").format((li?.first()?:0) / 100f)}"
//                        }else {
//                            holder.binding.tvProductPrice2.text = "${DecimalFormat("0.00").format((it.price?:0) / 100f)}"
//                        }
//                    }
//                } else {
//                    holder.binding.clProduct2.isVisible = false
//                }
//
//            } else {
//                holder.binding.clProduct1.isVisible = false
//                holder.binding.clProduct2.isVisible = false
//            }

        }

    }
}